<#-- 相互通话分析 -->
<#include "../../common/header.htm">
<div class="content-wrapper">
	<section class="content">
		<div class="row">
			<div class="bill-right-recall" style="background:#fff;">
				<form action="#" method="POST" id="listForm">
					<div class="box-header">
						<div class="row RowSearchWork">
							<div class="col-sm-12">
								<div class="form-group">
			                        <div class="form-inline">
			                        	<div class="form-group form-z">
			                                <label class="control-label">时间范围</label>
			                                <div class="input-group">
				                                <div class="input-icon-group">
				                                	<input type="text" class="form-control pull-right" name="startTime" value="${eocap.startTime!}" id="starTime" autocomplete="off" placeholder="请输入开始时间" >
											        <span id="scan" class="glyphicon glyphicon-calendar"> 
											        </span>
											    </div>
										    </div>
			                            </div>
			                            <div class="form-group">
			                                <label class="control-label hidden-xs">至</label>
			                                <div class="input-group">
				                                <div class="input-icon-group">
											        <input type="text" class="form-control pull-right" name="endTime" value="${eocap.endTime!}" id="endTime" autocomplete="off" placeholder="请输入结束时间" >
											        <span id="scan" class="glyphicon glyphicon-calendar"> 
											        </span>
											    </div>
										    </div>
			                            </div>
			                            <div class="form-group ml10">
			                                <label class="control-label hidden-xs">通话次数>=</label>
					                		<input type="number" class="form-control" name="callNumber" id="callNumber" value="${eocap.callNumber!}"/>
			                            </div>
			                            <div class="form-group bill-buttonarea" >
			                            	<input type="hidden" id="checkedAccount"/>
											<input type="button" class="btn btn-primary" onclick="eachOther.analysis();" value="分析" />
											<input type="button" class="btn btn-default" onclick="eachOther.reset()" value="重置" />
											<input type="button" class="btn btn-primary daobtn" onclick="eachOther.exportList('_table','相互通话分析');" value="导出" />
											<a style="display: none" target="_blank" id="_dow">dow</a>
										</div>
			                        </div>
		                        </div>
							</div>
						</div>
					</div>
					<div class="box-body">
						<div class="casemanage-switchtip">
							<div class="casemanage-zhexiantu active" :class="{active:showType==0}" @click="showType=0" title="切换为列表显示">
								<i class="casemanage-switchtip-list"></i><sapn>列表</sapn>
							</div>
							<!--<div class="casemanage-list active" onclick="eachOther.analysis();" title="切换列表显示">
								<i></i>
							</div>-->
							<div class="casemanage-relative" onclick="show()" title="切换为关系图显示">
								<i class="casemanage-switchtip-d3"></i><sapn>关系图</sapn>
							</div>
							<input type="hidden" id="showType" name="showType" value="${eocap.showType!}"/> 
						</div>
						<div id="list_table">
							<table class="table table-bordered table-striped table-hide" id="_table">
								<thead>
								<tr>
									<th data-options="field:'code'">机主号码</th>
									<th data-options="field:'name'">累计汇总</th>
								</tr>
								</thead>
								<tbody>
								<tr><td colspan="2">暂无数据</td></tr>
								</tbody>
							</table>
						</div>
					</div>
				</form>
			</div>
		</div>
	</section>
</div>
<script type="text/javascript">
	var caseId=parent.caseId;
	$(document).ready(function(){
		 $(window).resize(function(){
			$('#_table').datagrid('resize',{
                height:($(window).height())-($('.box-header').outerHeight(true))-30,
			});
		});
        var showType = $("#showType").val();
        if(showType == 0){
            $("#list_table").show();
        }
        eachOther.analysis();
	});
    function _checkedCallback(){
        eachOther.analysis();
    }
	function detailDialog(suspectPhone,suspectPhonePersonal) {
		let callNumber = $.trim($("#callNumber").val());
		let startTime = $.trim($("#startTime").val());
		let endTime = $.trim($("#endTime").val());
		var param = {
			callNumber: callNumber,
			startTime: startTime,
			endTime: endTime,
			suspectPhone: suspectPhone,
			caseId:caseId,
			suspectPhonePersonal: suspectPhonePersonal,
		};
		if(parent._checkedPhone.length>=1000){
			param.cardList="-1";//默认超过1000个节点为全选，不需要去后台传数据
		};
		var d = top.dialog({
			title : '相互通话分析详情',
			modal : true,
			url : '${ctx}/phoneAddress/eachOtherDetailsDialog',
			height : 800,
			width : 1500,
			data : param,
			onshow : function () {
			}
		});
		d.show();
		return false;
	}

	function show(){  //显示隐藏层和弹出层
		if(parent._checkedPhone.length < 2){
			toastr.error("请选择两个或两个以上手机号","提示信息");
			return false;
		}
		/**参数封装**/
		var data = {
			"startTime" : $("#starTime").val(),
			"checkedPhone" : parent._checkedPhone.join(','),
			callNumber:$("#callNumber").val(),
			caseId:caseId,
			"reqUrl" : '${ctx}/eachOtherCall/eachOtherCallAnalysis_d3'
		};
		var d = top.dialog({
			title : '相互通话分析关系图',
			modal : true,
			data : data,
			url : '${ctx}/eachOtherCall/eachOtherCallAnalysisD3Init',
			height : 800,
			width : 1500,
			onshow : function () {
			}
		});
		d.show();
		return false;
	}
	var idTmr;
	function  getExplorer() {
		var explorer = window.navigator.userAgent ;
		//ie
		if (explorer.indexOf("MSIE") >= 0) {
			return 'ie';
		}
		//firefox
		else if (explorer.indexOf("Firefox") >= 0) {
			return 'Firefox';
		}
		//Chrome
		else if(explorer.indexOf("Chrome") >= 0){
			return 'Chrome';
		}
		//Opera
		else if(explorer.indexOf("Opera") >= 0){
			return 'Opera';
		}
		//Safari
		else if(explorer.indexOf("Safari") >= 0){
			return 'Safari';
		}
	};

	/* 日期选择器start */
	$("#starTime").datepicker({
		format: "yyyy-mm-dd",
		autoclose: true,
		language:'zh-CN',
		pickerPosition:"bottom-left"
	});
	$("#endTime").datepicker({
		format: "yyyy-mm-dd",
		autoclose: true,
		language:'zh-CN',
		pickerPosition:"bottom-left"
	});
	/* 日期选择器end */
	var eachOther = {
		analysis : function(showType){
			if(parent._checkedPhone.length < 2){
				toastr.error("请选择两个或两个以上的手机号码进行分析","提示信息");
                $("#_table").html("<thead>\n" +
                    "<tr>\n" +
                    "<th data-options=\"field:'code'\">机主号码</th>\n" +
                    "<th data-options=\"field:'name'\">累计汇总</th>\n" +
                    "</tr>\n" +
                    "</thead>\n" +
                    "<tbody>\n" +
                    "<tr><td colspan=\"2\">暂无数据</td></tr>\n" +
                    "</tbody>");
				return false;
			}

			/**参数封装**/
			var data = {
				"startTime" : $("#starTime").val(),
				"checkedPhone" : parent._checkedPhone.join(','),
				caseId:caseId,
				callNumber:$("#callNumber").val()
			};
			$.ajax({
				type:"POST",
				url:"${ctx}/eachOtherCall/eachOtherCallAnalysis",
				data: JSON.stringify(data),
				dataType:"json",
				contentType:"application/json",
				success:function(results){
					if (results.result == "success") {
						var phone = results.data[0];
						var result = results.data[1];
						var foote = results.data[2];
						var col = new Array();
						var arr = new Array();
						//封装列
						col.push({"field":"criminal", "title":"机主号码"});
						$.each(phone,function(i,n) {
							var str = {"field":n,"title":n,"align":"center",
								formatter: function(value,row,index){
									if (row[value+"callNumber"]&&row[value+"callNumber"]!=0){
										var html = '';
										html  += '<a href="#" onclick="detailDialog(\''+row[value+"p"]+'\',\''+row[value]+'\')">';
										html  += '<span cc="'+row[value+"callNumber"]+'">通话'+row[value+"callNumber"]+'次</span>';
										html  += '<span cc="'+row[value+"caller"]+'">(主叫'+row[value+"caller"]+'次,被叫'+row[value+"called"]+'次)</span>';
										html  += '<span ss="'+row[value+"callSeconds"]+'">累计'+row[value+"callSeconds"]+'秒</span></a>';
										return html;
									} else if (row[value+"totalCallNumber"]&&row[value+"totalCallNumber"]!=0) {
										var html = '';
										html  += '<span cc="'+row[value+"totalCallNumber"]+'">通话'+row[value+"totalCallNumber"]+'次</span>';
										html  += '<span ss="'+row[value+"totalCallSeconds"]+'">累计'+row[value+"totalCallSeconds"]+'秒</span>';
										return html;
									} else {
										return "-";

									}
								}
							};
							col.push(str);
						});
						col.push({"field":"totalCallNumber", "title":"汇总累计","align":"center",
							formatter: function(value,row,index){
						    	var sum = row.sum;
								if (value&&value!=0){
									var html = '';
									html  += '<span cc="'+value+'">共通话'+value+'次</span>';
									html  += '<span ss="'+row.totalCallSeconds+'">累计'+row.totalCallSeconds+'秒</span>';
									return html;
								} else if (row[sum+"totalCallSeconds"]&&row[sum+"totalCallSeconds"]!=0) {
									var html = '';
									html  += '<span >共通话'+row[sum+"totalCallNumber"]+'次</span>';
									html  += '<span ss="'+row[sum+"totalCallSeconds"]+'">累计'+row[sum+"totalCallSeconds"]+'秒</span>';
									return html;
								}else {
									return "-";
								}
							}

						});
						//封装结果
						$.each(phone,function(pi,p) {
							var note ='{';
							note  += '"criminal":"'+p+'",';
							$.each(result,function(ri,e) {
								if (p == e.suspectPhone){
									$.each(e.ecaps,function(ri,ecap) {
										note  += '"'+ecap.suspectPhonePersonal+'":"'+ecap.suspectPhonePersonal+'",';
										note  += '"'+ecap.suspectPhonePersonal+'p":"'+p+'",';
										note  += '"'+ecap.suspectPhonePersonal+'callNumber":"'+ecap.callNumber+'",';
										note  += '"'+ecap.suspectPhonePersonal+'called":"'+ecap.called+'",';
										note  += '"'+ecap.suspectPhonePersonal+'caller":"'+ecap.caller+'",';
										note  += '"'+ecap.suspectPhonePersonal+'callSeconds":"'+ecap.callSeconds+'",';
									});
									note  += '"totalCallNumber":"'+e.totalCallNumber+'",';
									note  += '"totalCallSeconds":"'+e.totalCallSeconds+'",';
								}
							});
							note = note.substring(0,note.length-1);
							note += '}';
							arr.push(note);
						});
						//封装尾行
						var not ='{';
						not  += '"criminal":"汇总累计",';
						$.each(foote,function(i,f) {
							not  += '"'+f.suspectPhone+'totalCallNumber":"'+f.totalCallNumber+'",';
							not  += '"'+f.suspectPhone+'":"'+f.suspectPhone+'",';
							not  += '"'+f.suspectPhone+'totalCallSeconds":"'+f.totalCallSeconds+'",';
						})
                        not = not.substring(0,not.length-1);
                        not += '}';
                        arr.push(not);
						var jsonStr = '{"total":'+arr.length+',"rows":['+arr.join(",")+']}';

						var data = $.parseJSON(jsonStr);
						// $("#_table").append(html);
						//重新加载表格
						$('#_table').datagrid({
							fitColumns:true,
                            height:($(window).height())-($('.box-header').outerHeight(true))-30,
							singleSelect: true,
							// fit: true,
							singleSelect: true,
                            emptyMsg:"暂无信息",//加载数据为空时的信息
							showFooter:true,
							columns: [col],
                            onHeaderContextMenu: function(e, field){
                                e.preventDefault();
                                if (!cmenu){
                                    createColumnMenu("#dg1");
                                }
                                cmenu.menu('show', {
                                    left:e.pageX,
                                    top:e.pageY
                                });
                            }
							//onClickRow: onClickRow, //单击事件
						}).datagrid('loadData',data);

					}
					else {
						toastr.error("数据加载失败","提示信息");
					}
				},
				error:function(err){
					toastr.error("数据加载失败","提示信息");
				}
			});
		},
		details : function (suspectPhone,suspectPhonePersonal){
			var startTime = $("#starTime").val();
			var endTime = $("#endTime").val();
			var callNumber = $("#callNumber").val();
			var title = '通话详情';
			base.getView({
				url:"${ctx}/eachOtherCall/eachOtherDetailsInit?suspectPhone="+suspectPhone
					+"&suspectPhonePersonal="+suspectPhonePersonal
					+"&startTime="+startTime
					+"&endTime="+endTime
					+"&callNumber="+callNumber+"&caseId="+caseId,
				success:function(result){
					bootbox.dialog({
						title:title,
						message:result,
						size:"large",
						boxCss:{"width":"1270px"},
						closeButton : true
					})
				}
			});
		},
		reset : function(){
			$("#starTime").val('');
			$("#endTime").val('');
			$("#callNumber").val('');
		},
		exportList : function(tableid,excelName){
			if(getExplorer()=='ie') {
				var curTbl = document.getElementById(tableid);
				var oXL = new ActiveXObject("Excel.Application");

				//创建AX对象excel
				var oWB = oXL.Workbooks.Add();
				//获取workbook对象
				var xlsheet = oWB.Worksheets(1);
				//激活当前sheet
				var sel = document.body.createTextRange();
				sel.moveToElementText(curTbl);
				//把表格中的内容移到TextRange中
				sel.select;
				//全选TextRange中内容
				sel.execCommand("Copy");
				//复制TextRange中内容
				xlsheet.Paste();
				//粘贴到活动的EXCEL中
				oXL.Visible = true;
				//设置excel可见属性

				try {
					var fname = oXL.Application.GetSaveAsFilename(excelName+".xls", "Excel Spreadsheets (*.xls), *.xls");
				} catch (e) {
					print("Nested catch caught " + e);
				} finally {
					oWB.SaveAs(fname);

					oWB.Close(savechanges = false);
					//xls.visible = false;
					oXL.Quit();
					oXL = null;
					//结束excel进程，退出完成
					//window.setInterval("Cleanup();",1);
					idTmr = window.setInterval("Cleanup();", 1);
				}
			} else {
				tableToExcel(tableid,excelName)
			}
		}
	};
	function Cleanup() {
		window.clearInterval(idTmr);
		CollectGarbage();
	}
	/*
	template ： 定义文档的类型，相当于html页面中顶部的<!DOCTYPE> 声明。（个人理解，不确定）
	encodeURIComponent:解码
	unescape() 函数：对通过 escape() 编码的字符串进行解码。
	window.btoa(window.encodeURIComponent(str)):支持汉字进行解码。
	\w ：匹配包括下划线的任何单词字符。等价于’[A-Za-z0-9_]’
	replace()方法：用于在字符串中用一些字符替换另一些字符，或替换一个与正则表达式匹配的子串。
	{(\w+)}：匹配所有 {1个或更多字符} 形式的字符串；此处匹配输出内容是 “worksheet”
		正则中的() ：是为了提取匹配的字符串。表达式中有几个()就有几个相应的匹配字符串。
		讲解(/{(\w+)}/g, function(m, p) { return c[p]; } ：
	 /{(\w+)}/g 匹配出所有形式为“{worksheet}”的字符串；
	 function参数：  m  正则所匹配到的内容，即“worksheet”；
					 p  正则表达式中分组的内容,即“(\w+)”分组中匹配到的内容，为“worksheet”；
	 c ：为object，见下图3
	 c[p] : 为“worksheet”

	*/
	var tableToExcel = (function() {
		var uri = 'data:application/vnd.ms-excel;base64,',
			template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
			base64 = function(s) {
				return window.btoa(unescape(encodeURIComponent(s)))
			},
			// 下面这段函数作用是：将template中的变量替换为页面内容ctx获取到的值
			format = function(s, c) {
				return s.replace(/{(\w+)}/g,
					function(m, p) {
						return c[p];
					}
				)
			};
		return function(table, name) {
			if (!table.nodeType) {
				table = document.getElementById(table)
			}
			// 获取表单的名字和表单查询的内容
			var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
			// format()函数：通过格式操作使任意类型的数据转换成一个字符串
			// base64()：进行编码
			//window.location.href = uri + base64(format(template, ctx))
			document.getElementById("_dow").href = uri + base64(format(template, ctx));//必须是a标签，否则无法下载改名
			document.getElementById("_dow").download = name;
			document.getElementById("_dow").click();
		}
	})();
	//转换日期格式(时间戳转换为datetime格式)
	function changeDateFormat(cellval) {
		var dateVal = cellval + "";
		if (cellval != null) {
			var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
			var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
			var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

			var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
			var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
			var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
			return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
		}
	};
</script>
<style>
	.casemanage-switch .casemanage-relative {
		width: 90px;
		height: 35px;
	}
	.casemanage-switch.casemanage-switchtip {
		float: left;
	}
	.casemanage-switchtip {
		display: block;
	}
	#hidebg {
		position:absolute;
		left:0px;
		top:0px;
		background-color:#000;
		width: 100%;
		height: 100%;
		filter:alpha(opacity=60);  /*设置透明度为60%*/
		opacity:0.6;  /*非IE浏览器下设置透明度为60%*/
		display:none;
		z-Index:999;
	}
	#hidebox {
		text-align: right;
		position:absolute;
		width: 96%;
		height: 82%;
		top: 23px;
		left: 2%;
		border-radius: 5px;
		background-color:#fff;
		display:none;
		z-Index:9999;
		padding: 10px;
	}
	.outAccount_d3_head {
		float: left;
		font-size: 20px;
		margin-bottom: 5px;
	}
	#hidebox span{
		font-size: 20px;
	}
	svg {
		height: 96%;
		width: 100%;
	}
	.casemanage-relative:focus {
		border-color: #4695ed;
	}
	.control-label{
		font-size: 13px;
		font-weight: 400;
	}
	.box-header .form-group{
		margin-right: 15px;
	}
	.form-group.form-z {
		margin-right: 0px !important;
	}
	.bill-buttonarea .btn{
		margin-right: 12px;
		width: 70px;
	}
	.btn-primary:active:focus{
		background-color: #4695ed;
		border-color: #4695ed;
	}
	.box-body .title{
		font-size:14px;
		font-weight:800;
		line-height:30px;
	}
	.box-body .casemanage-switch{
		margin:0;
	}
	.casemanage-switch .casemanage-list.active {
		background-color: #4695ed;
	}
	.content {
		padding: 10px 25px 0 25px;
	}
	.table-hide td{
		text-align:center;
		vertical-align:middle;
	}
	td span{ display:block;}
	.btn-primary{
		background-color:#4695ed;
		border-color:#4695ed;
	}
	.btn-primary:hover, .btn-primary:active, .btn-primary.hover{
		background-color:#61a8f5;
		border-color:#61a8f5;
	}
	.btn-primary.focus, .btn-primary:focus{
		background-color:#4695ed;
		border-color:#4695ed;
	}
	.casemanage-switch .casemanage-list{
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
		border-top-left-radius: 5px;
		border-bottom-left-radius: 5px;
	}
	.form-control{
		border-radius:4px;
	}
	.input-group .form-control:first-child{
		border-top-right-radius:4px;
		border-bottom-right-radius: 4px;
	}
	.form-control{
		border-radius:4px;
		font-size: 12px;
		border-color: #e4e4e4;
	}
	.input-group .form-control:first-child{
		border-top-right-radius:4px;
		border-bottom-right-radius: 4px;
	}
	.form-control:focus{
		border-color:#4695ed;
	}
	.form-control:hover{
		border-color:#4695ed;
	}
	.bill-right{
		margin-left: 255px;
	}
	.casemanage-relative {
		border-top-right-radius: 5px;
		border-bottom-right-radius: 5px;
	}
</style>